<template>
  <el-card>
    <div class="aaa">
      <button @click="selectAll()">全选</button>
      <button @click="erasure()">批量删除</button>
      <button @click="addData">添加数据</button>
    </div>

    <div class="box" v-for="(item, index) in foods.data" key="item.id" style="display: flex; align-items: center; margin: 20px">
      <input type="checkbox" v-model="item.checked" />
      <div>名字：{{ item.title }}</div>
      <div>价格：{{ item.price }}</div>
      <div>
        <button @click="add(index)">+</button>
        <a>数量:{{ item.count }}</a>
        <button @click="del(item)">-</button>
        <button @click="modifyData(item)" style="margin-left: 20px">修改数据</button>
      </div>
    </div>
    <div class="box" style="display: flex; align-items: center">
      <div>已选：{{ num }}</div>
      <div>总价：{{ total }}</div>
      <button :disabled="!num">结算</button>
    </div>
    <!-- 弹窗 -->
    <pop ref="popRef" @add-data="handleAddData"></pop>
    <br />
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import pop from "./pop.vue";
let popRef = ref(null);
// 假数据
let foods = ref({
  data: [
    { id: "husky", title: "哈士奇狗", price: 50, nums: 10 },
    { id: "car", title: "玩具车", price: 10, nums: 15 },
    { id: "milk", title: "牛奶", price: 30, nums: 5 },
  ],
});
// 添加
let add = (index) => {
  foods.value.data[index].count++;
};
let del = (item) => {
  if (item.count > 1) {
    item.count--;
  }
};
let num = computed(() => foods.value.data.filter((item) => item.checked).length);

// 总价
let total = computed(() => {
  let a = 0;
  foods.value.data
    .filter((item) => item.checked)
    .forEach((item) => {
      a += item.price * item.count;
    });
  return a;
});
let selectAlls = ref(false);
// 全选
const selectAll = () => {
  selectAlls.value = !selectAlls.value;
  foods.value.data.forEach((item) => {
    item.checked = selectAlls.value;
  });
};
//  处理子组件触发的事件
const handleAddData = (newData) => {
  console.log(newData, 1112);
};
const addData = (newData) => {
  if (newData) {
    const id = `${Date.now()}-${Math.floor(Math.random() * 100000)}`;
    const dataWithId = { id:id,...newData };
    console.log(dataWithId,123);
    
    foods.value.data.push(dataWithId)
    
  }

  popRef.value.open();
};

const modifyData = (row) => {
  popRef.value.open({ ...row });
};
// 批量删除
const erasure = () => {
  foods.value.data = foods.value.data.filter((item) => !item.checked);
};
// 添加count与checked属性
onMounted(() => {
  foods.value.data.forEach((item) => {
    item.count = 1;
    item.checked = false;
  });
});
</script>

<style lang="scss" scoped>
.box > div {
  margin-left: 20px;
}
.aaa > button {
  margin-right: 20px;
}
</style>
